package com.pbs.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.pbs.net.WSF;
import com.pbs.packdata.UserInfo;
import com.pbs.ui.dialog.Dialog;
import com.pbs.ui.dialog.Dialog.Type;

public class FriendListActivity extends Activity implements OnItemClickListener {

	private ArrayList<UserInfo> items = new ArrayList<UserInfo>();
	private ListView lv;
	private ArrayAdapter<UserInfo> aa;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_list);
		lv = (ListView) findViewById(R.id.List);
		try {
			items = WSF.getListUsername(AccountManagerScreen.getUserID());
			if (!items.isEmpty()) {
				((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
			} else {
				((TextView) findViewById(R.id.tvMessageEmptyList))
						.setText("Don't have any friends");
			}
			aa = new ArrayAdapter<UserInfo>(this, R.layout.item_username_info,
					items) {

				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_username_info, null);
					}
					UserInfo info = items.get(position);

					if (info != null) {
						TextView display_name = (TextView) v
								.findViewById(R.id.tvTopLeftInfo);
						TextView username = (TextView) v
								.findViewById(R.id.tvBottomRightInfo);
						CheckBox cb = (CheckBox) v
								.findViewById(R.id.chkSelectContact);
						cb.setChecked(info.isChecked());
						display_name.setText(info.getDisplayname());
						username.setText(info.getUsername());
					}
					return v;
				}
			};
			lv.setAdapter(aa);
			lv.setOnItemClickListener(this);
		} catch (Exception e) {
			Dialog.show(this, "Error!", e.getMessage(), null, null, null, null,
					Type.ERROR);
		}
	}

	private void addUserDialog() {
		LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View content = vi.inflate(R.layout.add_friend, null);

		final EditText inputBoxUsername = (EditText) content
				.findViewById(R.id.txtUsername);
		final EditText inputBoxDisplayName = (EditText) content
				.findViewById(R.id.txtDisplayname);

		if (!items.isEmpty()) {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
		} else {
			((TextView) findViewById(R.id.tvMessageEmptyList))
					.setText("Don't have any items");
		}
		new AlertDialog.Builder(this).setView(content).setTitle("Add friend")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface d, int which) {
						String username = inputBoxUsername.getText().toString()
								.trim();
						String display_name = inputBoxDisplayName.getText()
								.toString().trim();
						if (username.equals("")) {
							Toast.makeText(FriendListActivity.this,
									"Please enter username", Toast.LENGTH_LONG);
							return;
						} else {
							try {
								WSF.Result result = WSF.addUser(
										AccountManagerScreen.getUserID(),
										username, display_name);
								if (result == WSF.Result.SUCCESSED) {
									FriendListActivity.this.items = WSF
											.getListUsername(AccountManagerScreen
													.getUserID());
									Toast
											.makeText(
													FriendListActivity.this,
													"Added '"
															+ (display_name
																	.trim()
																	.equals("") ? username
																	: display_name
																			.trim())
															+ "'",
													Toast.LENGTH_LONG);
									FriendListActivity.this
											.onCreate(FriendListActivity.this
													.getIntent().getExtras());
								} else if (result == WSF.Result.FAILED) {
									Toast.makeText(FriendListActivity.this,
											"Add failed!", Toast.LENGTH_LONG);
								} else {
									Toast
											.makeText(
													FriendListActivity.this,
													"Exception when attempting query to database",
													Toast.LENGTH_LONG);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}

					}
				}).setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface d, int which) {
								d.dismiss();
							}
						}).create().show();
	}

	private void editFriendDialog(final UserInfo info) {
		final LinearLayout ll = new LinearLayout(this);
		final EditText inputBoxDisplayName = new EditText(this);

		inputBoxDisplayName.setText(info.getDisplayname());

		ll.setOrientation(LinearLayout.VERTICAL);
		ll.setPadding(5, 5, 5, 5);
		ll.addView(inputBoxDisplayName, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));

		inputBoxDisplayName.setSingleLine(true);

		inputBoxDisplayName.setHint("Display name");
		new AlertDialog.Builder(this).setView(ll).setTitle(
				"Edit " + info.getUsername()).setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface d, int which) {
						String display_name = inputBoxDisplayName.getText()
								.toString().trim();
						try {
							WSF.Result result = WSF.updateUser(
									AccountManagerScreen.getUserID(),
									display_name, info.getId());
							if (result == WSF.Result.EXCEPTION) {
								Toast.makeText(FriendListActivity.this,
										"Error when attempting update",
										Toast.LENGTH_LONG);
							} else if (result == WSF.Result.FAILED) {
								Toast.makeText(FriendListActivity.this,
										"Update failed!", Toast.LENGTH_LONG);
							} else {
								info.setDisplayName(display_name);
								aa.notifyDataSetChanged();
								Toast
										.makeText(FriendListActivity.this,
												"Updated '"
														+ display_name.trim()
														+ "'",
												Toast.LENGTH_LONG);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}).setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface d, int which) {
						d.dismiss();
					}
				}).create().show();
	}

	public void addUsernameClick(View v) {
		addUserDialog();
	}

	public void removeUsernameClick(View v) {
		if (items.isEmpty()) {
			Toast.makeText(FriendListActivity.this,
					"There aren't any a-friends here!", Toast.LENGTH_LONG);
			return;
		}
		if (numberOfItemsSelected == 0) {
			Toast.makeText(FriendListActivity.this, "Please choose any items",
					Toast.LENGTH_LONG);
			return;
		}

		Dialog.show(this, "Confirm", "Do you want to remove?", "Yes", "No",
				new OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						int removed = 0;
						for (int i = 0; i < items.size(); i++) {
							if (items.get(i).isChecked()) {
								try {
									int count = WSF.removeUser(
											AccountManagerScreen.getUserID(),
											items.get(i).getUsername());
									if (count > 0) {
										removed++;
										items.remove(i);
										i -= count;
										numberOfItemsSelected -= count;
										aa.notifyDataSetChanged();
									} else {
									}
								} catch (Exception e) {
									Dialog.show(FriendListActivity.this,
											"Error!", "UMA-165: "
													+ e.getMessage(), null,
											null, null, null, Type.ERROR);
								}
							}
						}
						Toast.makeText(FriendListActivity.this, "Removed "
								+ removed
								+ (removed > 1 ? " elements" : "element"),
								Toast.LENGTH_LONG);
						if (!items.isEmpty()) {
							((TextView) findViewById(R.id.tvMessageEmptyList))
									.setText("");
						} else {
							((TextView) findViewById(R.id.tvMessageEmptyList))
									.setText("Don't have any items");
						}
					}
				}, new OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}, Type.CONFIRM);
	}

	private int numberOfItemsSelected = 0;

	public void radioButtonClick(View v) {
		CheckBox cb = (CheckBox) v;
		int pos = lv.getPositionForView(v);
		items.get(pos).setChecked(cb.isChecked());
		numberOfItemsSelected += cb.isChecked() ? 1 : -1;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		editFriendDialog(items.get(arg2));
	}
}
